const shellHelper = require('../libs/shellHelper')
const inquirer = require('inquirer');
const chalk = require('chalk');
const path = require('path');
const fs = require('fs');
const ora = require('ora');
const spinner = ora();
const Listr = require('listr');
const execa = require('execa');
const GIT_REPOSITORY = 'https://gitee.com/roft/gitDo.git';

const exit = () => Promise.reject('break')
//todo:实现一个识别读文件、读单个或多个的方法

function sleep(ms) {
  return new Promise(resolve => {
    setTimeout(resolve, ms);
  })
}

const processRemote = dir => (stdout, next) => {
  stdout = stdout || shellHelper.shell.exec('git remote', { cwd: dir }).stdout
  next(stdout.split(/[\n\s\r]/).filter(val => !!val))
}

const pullRemote = dir => (stdout, next) => {
  const cmds = stdout.map(remote => ({ cmd: `git pull ${remote} master`, cwd: dir }))
  shellHelper.series(cmds, next)
}

// const commitRemote = dir => (stdout, next) => {
//   const cmds = stdout.map(remote => ({ cmd: `cli commit 'auto commit'`, cwd: dir }))
//   shellHelper.series(cmds, next)
// }

const inquirerGitPulls = async (filname) => {
  const promptList = [
    {
      type: 'input',
      message: '请输入文件地址(可不填):',
      name: 'filname',
      default: "pulldirs.json" // 默认值
    }]

  const gitPulls = filname => {
    let data = fs.readFileSync(filname)
    let dirs = JSON.parse(data)
    let env = process.platform.includes("darwin") ? 'mac' : "windows"
    const cmds = Object.values(dirs[env]).map(dir => ([processRemote(dir), pullRemote(dir)]))
    shellHelper.series(cmds)
  }

  if (!filname) {
    const result = await inquirer.prompt(promptList)
    filname = result.filname
  }
  gitPulls(filname)
}

const inquirerGitCommits = async (filname) => {
  const promptList = [
    {
      type: 'input',
      message: '请输入文件地址(可不填):',
      name: 'filname',
      default: "pulldirs.json" // 默认值
    }]

  const gitCommits = filname => {
    let data = fs.readFileSync(filname)
    let dirs = JSON.parse(data)
    let env = process.platform.includes("darwin") ? 'mac' : "windows"
    // const { stdout } = shellHelper.serie("git", ['remote'])
    // const cmds = stdout.split(/[\s\n\r]/)
    console.info(data, dirs[env])
    const cmds = Object.values(dirs[env]).map(dir => ({ cmd: `cli commit "auto commit"`, cwd: dir }))
    shellHelper.series(cmds)
  }

  if (!filname) {
    const result = await inquirer.prompt(promptList)
    filname = result.filname
  }
  gitCommits(filname)
}

const inquirerGitCommit = async message => {
  const promptList = [
    {
      type: 'input',
      message: '请输入提交信息(可不填):',
      name: 'message',
      default: "auto commit" // 默认值
    }]
  const gitCommit = message => {
    let pushs = shellHelper.shell.exec('git remote').stdout.split(/[\n\s\r]/).filter(val => !!val).map(remote => `git push ${remote}`)

    shellHelper.series([
      // 'which git',
      'git pull',
      'git add .',
      `git commit -m "${message || "auto commit"}"`,
      ...pushs
    ])

  }
  if (!message) {
    const result = await inquirer.prompt(promptList)
    message = result.message
  }
  gitCommit(message)
}
const gitCloneAndInstall = async (url, branch, directory) => {
  const isYarn = fs.existsSync('./yarn.lock')
  const isNpm = fs.existsSync('./package-lock.json')
  const cmds = [
    { cmd: `git clone --recursive -b ${branch} ${url} ${directory}`, stdio: 'inherit' },
  ];
  (isYarn || isNpm) && cmds.push({ cmd: `${isYarn ? 'yarn' : 'npm'} install`, stdio: 'inherit', cwd: directory, })

  shellHelper.series(cmds)
}

const gitClone = async (url, branch, directory) => {
  spinner.start(`模版下载中`)
  return shellHelper.execa('git', ['clone', `${url}`, `-b`, `${branch}`, `${directory}`])
}

const install = async (directory) => {
  const isYarn = fs.existsSync('./yarn.lock')
  const isNpm = fs.existsSync('./package-lock.json')

  if (isYarn || isNpm) {
    spinner.start(`依赖安装中`)
    await sleep(1000)
    return shellHelper.execa(`${isYarn ? 'yarn' : 'npm'}`, [`install`], { cwd: directory, })
  }
}

const clearGit = async (directory) => {
  spinner.start(`git清理中`)
  return shellHelper.execa(`rm`, ['-rf', '.git/'], { cwd: directory, })
}

const inquirerGitClone = async (dirname) => {
  const promptList = [{
    type: 'rawlist',
    message: '请选择一种模版:',
    name: 'template',
    choices: [
      "t1",
      "Pear",
      "Banana"
    ]
  }];

  const directory = path.format({
    dir: process.cwd(),
    name: dirname || path.parse(GIT_REPOSITORY).name,
  })

  const { template: branch } = await inquirer.prompt(promptList)
  // gitCloneAndInstall(GIT_REPOSITORY, branch, directory)

  try {
    (await gitClone(GIT_REPOSITORY, branch, directory)).exitCode === 0 && spinner.succeed(`下载完成`);
    (await install(directory)).exitCode === 0 && spinner.succeed(`依赖安装完成`);
    (await clearGit(directory)).exitCode === 0 && spinner.succeed(`git清理完成`);
    console.log(`\n${chalk.green('成功!')} 项目准备完毕`)
    console.log(`\ncd ${dirname} && yarn start\n`)
  } catch (error) {
    spinner.fail();
    console.log('😫', error);
  }
}

const inquirerDirDel = async (dirname) => {
  const promptList = [{
    type: 'input',
    message: '请输入文件或目录地址:',
    name: 'dirname',
    validate: function (val) {
      if (val.match(/^$|(^\s+)|(\s+$)/g)) { // 非空非头尾空格
        return "请正确输入";
      }
      return true;
    }
  }]
  const DirDel = (dirname) => {
    spinner.start(`${dirname}删除中`)
    const { code } = shellHelper.shell.rm('-rf', dirname)
    code === 0 && spinner.succeed(`${dirname}删除成功`)
  }
  if (!dirname) {
    const result = await inquirer.prompt(promptList)
    dirname = result.dirname
  }

  DirDel(dirname)
}

const inquirerGitCreate = async (dirname) => {
  const promptList = [{
    type: 'input',
    message: '请输入目录名称:',
    name: 'dirname',
    validate: function (val) {
      if (val.match(/^$|(^\s+)|(\s+$)/g)) { // 非空非头尾空格
        return "请正确输入";
      }
      return true;
    }
  }]
  const repoCreate = (dirname) => {
    let listr = new Listr(
      [
        // {
        //   title: '创建文件夹',
        //   task: () => execa('mkdir', [dirname])
        // },
        // {
        //   title: '进入文件夹',
        //   // task: () => sleep(1000).then(()=>execa('cd', [`./${dirname}`]))
        //   task: () => shellHelper.seriesa([`cd ./${dirname}`])
        //   // task: () => shellHelper.shell.cd(`./${dirname}`)
        // },
        // {
        //   title: '初始化git项目',
        //   task: () => execa('git', ['init'], { cwd: dirname })
        // },
        // {
        //   title: '同步远程仓库',
        //   task: async () => {
        //     const result = await inquirer.prompt([{
        //       type: 'input',
        //       message: '请输入远程仓库地址(支持多个|隔开):',
        //       name: 'remoteUrls',
        //       validate: function (val) {
        //         if (val.match(/^$|(^\s+)|(\s+$)/g)) { // 非空非头尾空格
        //           return "请正确输入";
        //         }
        //         return true;
        //       }
        //     }])
        //     const cmds = result.remoteUrls.split('|').map((remoteUrl, i) => ({
        //       title: `远程库${i + 1}`,
        //       task: () => sleep(1000).then(() => execa('git', ['remote', 'add', `origin${i > 0 ? i : ''}`, remoteUrl], { cwd: dirname }))
        //     }))

        //     return new Listr(cmds, { concurrent: true })
        //   }
        // },
        {
          title: '将远程仓库的文件拉取到本地仓库',
          task: async () => {
            const { stdout } = await execa("git", ['remote'])
            const cmds = stdout.split(/[\s\n\r]/).map((remoteUrl, i) => ({
              title: `远程库${i + 1}`,
              task: () => sleep(1000).then(() => execa('git', ['pull', remoteUrl, 'master', '--allow-unrelated-histories'], { cwd: dirname }))
            }))
            return new Listr(cmds, { concurrent: true })
          }
        },
        // {
        //   title: '初始化node项目',
        //   task: () => execa('yarn', ['init', '-y'], { cwd: dirname })
        //   // task: () => shellHelper.seriesa([`yarn init -y`])
        // },
        // {
        //   title: '提交所有变化到暂存区',
        //   task: () => execa('git', ['add', '.'], { cwd: dirname })
        // },
        // {
        //   title: '提交到本地仓库',
        //   task: () => execa('git', ['commit', '-m', 'initial commit'], { cwd: dirname })
        // },
        // {
        //   title: '推送到到远程仓库',
        //   task: () => execa('git', ['push', '--set-upstream', 'origin', 'master'], { cwd: dirname })
        // },
      ]
    )

    listr.run()
  }
  if (!dirname) {
    const result = await inquirer.prompt(promptList)
    dirname = result.dirname
  }
  repoCreate(dirname)
}
module.exports = {
  inquirerGitClone,
  inquirerGitCommit,
  inquirerGitCommits,
  inquirerDirDel,
  inquirerGitCreate,
  inquirerGitPulls
}

// fs.readFile('test1.json','utf8',function (err, data) {
//   if(err) console.log(err);
//   var test1=JSON.parse(data);
//   test1.name="li";
//   var t = JSON.stringify(test1);
//   fs.writeFileSync('test1.json',t)
// });